import { getOutbound,outbound} from '@/axios/api/slot_management/slot_outbound'
import { ElNotification } from 'element-plus';
import { useSlotManagementStore } from '@/store/slot_mangement';
const SlotManagementStore = useSlotManagementStore();

export default function () {

    

    // 刷新
    async function handgetoutbound() {
        SlotManagementStore.locationtableData_pinia2=[]
        try {
            let res: any = await getOutbound();
            if (res.code === 200) {
                SlotManagementStore.locationtableData_pinia2 = JSON.parse(res.data);
                return 'ok';
            }else {
                ElNotification({
                    title: 'Error',
                    message: 'Failed to get outbound',
                    type: 'error',
                })
                return Promise.reject(new Error('Failed to get outbound'))
            }
            
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
            return Promise.reject(new Error(error))
        }
    }

    // 出库
    async function handaddoutbound(ConCaseNo: string) {
        // 判断SlotManagementStore.locationtableData_pinia2中是否有该ConCaseNo
        let flag = false;
        for (let i = 0; i < SlotManagementStore.locationtableData_pinia2.length; i++) {
            if (SlotManagementStore.locationtableData_pinia2[i].ConCaseNo === ConCaseNo) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            return 'no'
        }
        try {
            let res: any = await outbound({
                ConCaseNo: ConCaseNo
            });
            if (res.code === 200) {
                // 从SlotManagementStore.locationtableData_pinia2中删除该ConCaseNo
                for (let i = 0; i < SlotManagementStore.locationtableData_pinia2.length; i++) {
                    if (SlotManagementStore.locationtableData_pinia2[i].ConCaseNo === ConCaseNo) {
                        SlotManagementStore.locationtableData_pinia2.splice(i, 1);
                        break;
                    }
                }
                return 'ok';
            }else {
                return Promise.reject(new Error('Failed to add outbound'))
            }
            
        } catch (error: any) {
            return Promise.reject(new Error(error))
        }
    }

   
    

    return {
        handgetoutbound,
        handaddoutbound,
    }
}